package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @Author:Mr.m
 * @Date: 2025-10-11 11:37
 * @Description:
 */
@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    private static final String LOGIN_PATH = "/login";
    private static final String TOKEN_HEADER_NAME = "token";

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //1.将请求对象和响应对象转换为HttpServletRequest和HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //2.获取请求路径
        String path = request.getRequestURI();
        log.info("---拦截到的请求路径是：{} ---", path);
        //3.判断当前请求是否位登录请求 /login
        boolean isLoginReq = ObjectUtil.equals(LOGIN_PATH, path);
        if (isLoginReq) {
            chain.doFilter(request, response);
            return;
        }
        //4. 不是登录请求获取请求头中名字叫 token 的请求头
        String token = request.getHeader(TOKEN_HEADER_NAME);
        //4.1判断token是否为空
        if (ObjectUtil.isEmpty(token)) {
            response.setStatus(401);
            return;
        }
        //5.验证 token
        try{
            Claims claims = JwtUtil.parseToken(token);
            //获取用户信息
            String username = claims.get("username", String.class);
            log.info("---当前用户是：{} ---", username);
            Object id = claims.get("id");
            log.info("---当前用户id是：{} ---", id);
            //放行
            chain.doFilter(request, response);
        } catch (Exception e) {
          log.error("---token验证失败---");
          response.setStatus(401);
          return;
        }


    }
}
